import $ from '../../utils/tool'
import * as echarts from '../../components/ec-canvas/echarts'
const util = require('../../utils/util.js')
const app = getApp()
// 柱状图bar
let barCategories = null
let barSeriesData = null

// 折线图line
let lineCategories = null
let lineSeriesData = null

// 饼图pie
let pieSeries = null

Page({
  data: {
    logs: [],
    todayLogs: [],
    today: '',
    activeIndex: 0,
    totalFocusNumber: 0,
    totalFocusTime: 0,
    todayFocusNumber: 0,
    todayFocusTime: 0,
    showTotalFocusTime: 0,
    showTodayFocusTime: 0,
    ecBar: {
      onInit: (canvas, width, height, dpr) => {
        const barChart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });
        canvas.setChart(barChart);
        barChart.setOption(getBarOption());

        return barChart;
      }
    },
    ecLine: {
      onInit: function (canvas, width, height, dpr) {
        const lineChart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });
        canvas.setChart(lineChart);
        lineChart.setOption(getLineOption());

        return lineChart;
      }
    },
    ecPie: {
      onInit: function (canvas, width, height, dpr) {
        const pieChart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });
        canvas.setChart(pieChart);
        pieChart.setOption(getPieOption());
        
        return pieChart;
      }
    }
  },
  onShow() {
    this.setData({
      today: util.dateFormat('YYYY年mm月dd日')
    })
    this.getLogs()
    this.handleData()
    const obj = {currentTarget: {dataset: {index: 0}}}
    this.changeType(obj)
  },
  // 获取主页得到的记录
  getLogs() {
    let logs = app.globalData.logs
    let totalFocusTime = app.globalData.totalFocusTime
    let totalFocusNumber = app.globalData.totalFocusNumber
    let todayLogs = app.globalData.todayLogs
    let todayFocusTime = app.globalData.todayFocusTime
    let todayFocusNumber = app.globalData.todayFocusNumber
    let showTotalFocusTime = util.secondFormat(totalFocusTime)
    let showTodayFocusTime = util.secondFormat(todayFocusTime)
    this.setData({
      logs: logs,
      totalFocusTime: totalFocusTime,
      totalFocusNumber: totalFocusNumber,
      todayLogs: todayLogs,
      todayFocusTime: todayFocusTime,
      todayFocusNumber: todayFocusNumber,
      showTotalFocusTime: showTotalFocusTime, //展示专注总时间
      showTodayFocusTime: showTodayFocusTime
    })
  },

  // 专注时段分布 0为今日，1为总共
  changeType(e) {
    this.setData({
      activeIndex: e.currentTarget.dataset.index
    })
    // this.handleData()
  },

  handleData() {
    let windowWidth = app.globalData.windowWidth;
    // -----------------------------总共（折线图date、饼图name）----------------------------------
    let logs = this.data.logs // 这里logs一般为偶数
    let newLogs = []
    for (let i = 0; i < logs.length; ){
      let name = logs[i].name //专注的时间名字
      let startTime = logs[i].startTime //专注的时间名字
      newLogs.push({name: name, startDate: util.dateFormat('mm-dd' ,new Date(startTime)), focusTime: Math.round((logs[i].startTime - logs[i+1].startTime) / 1000)})
      i = i + 2
    }
    pieSeries = []
    lineCategories = []
    lineSeriesData = []
    newLogs.forEach((item) => {
      // 饼图
      let isAdded = false
      for(let j = 0; j < pieSeries.length; j++) {
        if(item.name == pieSeries[j].name) {
          pieSeries[j].value += item.focusTime
          isAdded = true
          break
        }
      }
      if(isAdded == false) { //数据尚未加入
        let newSerie = { value: item.focusTime, name: item.name }
        pieSeries.push(newSerie)
      }else if (isAdded == true) { //数据已经加入
        isAdded = false //重置,给下一个用
      }
      
      // 折线图-需要date
      if(lineCategories.indexOf(item.startDate) == -1) { //不存在
        lineCategories.push(item.startDate)
        lineSeriesData.push(item.focusTime)
      }else {
        for(let i = 0; i < lineCategories.length ; i++) {
          if(lineCategories[i] == item.startDate) {
            lineSeriesData[i] += item.focusTime
          }
        }
      }
    })

    // 折线图实现-总共
    let lineSortList = []  // 时间从小到大排序
    lineCategories.forEach((item, index) => {
      lineSortList.push({categories: item, seriesData: lineSeriesData[index]})
    })
    let compare = (obj1, obj2) => {
      let val1 = obj1.categories
      let val2 = obj2.categories
      if(val1 < val2) { return -1 }
      else if(val1 > val2) { return 1 }
      else { return 0 }
    }
    lineSortList = lineSortList.sort(compare)
    lineCategories = []
    lineSeriesData = []
    lineSortList.forEach(item => {
      lineCategories.push(item.categories)
      lineSeriesData.push(item.seriesData)
    })

    // -----------------------------今日（柱状图）----------------------------------
    let todayLogs = this.data.todayLogs
    let newTodayLogs = []
    for (let i = 0; i < todayLogs.length; ){
      let name = todayLogs[i].name //专注的时间名字
      let startTime = todayLogs[i].startTime //专注的时间名字
      newTodayLogs.push({name: name, startHour: util.dateFormat('HH点' ,new Date(startTime)),focusTime: Math.round((logs[i].startTime - todayLogs[i+1].startTime) / 1000)})
      i = i + 2
    }

    barCategories = []
    barSeriesData = []
    newTodayLogs.forEach((item) => {
      // 柱状图
      if(barCategories.indexOf(item.startHour) == -1) { //不存在
        barCategories.push(item.startHour)
        barSeriesData.push(item.focusTime)
      }else {
        for(let i = 0; i < barCategories.length ; i++) {
          if(barCategories[i] == item.startHour) {
            barSeriesData[i] += item.focusTime
          }
        }
      }
    })
    // 柱状图实现-今日
    let barSortList = []  // 时间从小到大排序
    barCategories.forEach((item, index) => {
      barSortList.push({categories: item, seriesData: barSeriesData[index]})
    })
    barSortList = barSortList.sort(compare)
    barCategories = []
    barSeriesData = []
    barSortList.forEach(item => {
      barCategories.push(item.categories)
      barSeriesData.push(item.seriesData)
    })
  },
  
  // 清除记录
  clearLog() {
    wx.showModal({
      title: '提示',
      content: '是否删除记录？此操作不可恢复！',
      success: res => {
        if (res.confirm) {
          getApp().globalData.logs = []
          $.storage.set('logs', [])
          this.getLogs()
          wx.showToast({
            title: '清除成功',
          })
        }
      }
    })
  },
})


function getBarOption() {
  return {
    tooltip: {
      trigger: 'axis',
      axisPointer: {            // 坐标轴指示器，坐标轴触发有效
        type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
      }
    },
    grid: {
      left: 0,
      right: 0,
      bottom: 10,
      top: 10,
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: barCategories
    },
    yAxis: {
      type: 'value'
    },
    series: [{
      data: barSeriesData,
      type: 'bar',
      showBackground: true,
      backgroundColor: 'transparent',
    }]
  };
}
function getLineOption() {
  return {
    tooltip: {
      trigger: 'item',
      axisPointer: {            // 坐标轴指示器，坐标轴触发有效
        type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
      }
    },
    grid: {
      left: 0,
      right: 0,
      bottom: 15,
      top: 10,
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: lineCategories
    },
    yAxis: {
      type: 'value'
    },
    series: [{
      data: lineSeriesData,
      type: 'line'
    }]
  };
}
function getPieOption() {
  return {
    backgroundColor: 'transparent',
    series: [{
      label: {
        normal: {
          fontSize: 14
        }
      },
      type: 'pie',
      center: ['50%', '50%'],
      radius: ['50%', '70%'],
      data: pieSeries
    }]
  };
}